#include <stdbool.h>
#include <stdio.h>
#include "verify_utf8.h"

bool isValidUtf8(const char *str) {
    unsigned char *bytes = (unsigned char *)str;
    unsigned int codepoint, min_val;
    int bytes_in_sequence = 0;

    while (*bytes != '\0') {
        if (*bytes < 128) { // 1-byte character (ASCII)
            bytes++;
        } else if ((*bytes & 0xE0) == 0xC0) { // 2-byte character
            bytes_in_sequence = 1;
            min_val = 0x80;
            codepoint = *bytes & 0x1F;
        } else if ((*bytes & 0xF0) == 0xE0) { // 3-byte character
            bytes_in_sequence = 2;
            min_val = 0x800;
            codepoint = *bytes & 0x0F;
        } else if ((*bytes & 0xF8) == 0xF0) { // 4-byte character
            bytes_in_sequence = 3;
            min_val = 0x10000;
            codepoint = *bytes & 0x07;
        } else {
            return false; // Invalid UTF-8 header byte
        }

        bytes++;
        for (int i = 0; i < bytes_in_sequence; i++) {
            if ((*bytes & 0xC0) != 0x80) {
                return false; // Invalid UTF-8 continuation byte
            }
            codepoint = (codepoint << 6) | (*bytes & 0x3F);
            bytes++;
        }
        if (codepoint < min_val) {
            return false; // Overlong encoding
        }
    }
    return true; // String is valid UTF-8
}
